// 账户体系模块-mysql服务处理

// 引入数据库模块
const db = require('../config/mysql.js')
const utils = require("../common/utils")
const bcrypt = require('bcryptjs')
// 引入jwt
const jwt = require('jsonwebtoken')
const secretKey = 'ethink'    // 密钥

// 存储验证码
const setQrCode = (email, qrcode) => {
  return new Promise((resolve, reject) => {
    try {
      db.query(`select email from qrcode where email = "${email}"`, (err, result) => {
        if (result.length > 0) {
          let sql = `update qrcode set qrcode = ${qrcode} where email = "${email}"`
          db.query(sql, (err, res) => {
            if (res.affectedRows === 1) resolve(true)
          })
        } else {
          let sql = `insert into qrcode values("${email}", "${qrcode}")`
          db.query(sql, (err, res) => {
            if (res.affectedRows === 1) resolve(true)
          })
        }
      })
    } catch (e) {
      reject(false)
    }
  })
}

// 获取验证码
const getQrCode = (email) => {
  return new Promise((resolve, reject) => {
    let sql = `select qrcode from qrcode where email = "${email}"`
    try{
      db.query(sql, (err, result) => {
        if (err) return reject(err)
        if (result.length == 1) {
          let qrcode = result[0].qrcode
          return resolve(qrcode)
        } else {
          return resolve()
        }
      })
    }catch(e){
       return reject()
    }
  })
}

// 注册
const register = (user_name, email, password) => {
  let uuid = `167${utils.randomNumber()}${utils.randomNumber()}`
  let register_time = utils.formatDate(new Date().getTime())
  return new Promise((resolve, reject) => {
    db.query(`select email from user where email = "${email}"`, (err, result) => {
      if (err) return reject(err)
      if (result.length >= 1) return resolve("邮箱已被注册")
      // 邮箱不存在
      password = bcrypt.hashSync(password, 10)
      let sql = `insert into user (id, user_name, email, password, register_time) values(?,?,?,?,?)`
      db.query(sql, [uuid, user_name, email, password, register_time], (err1, res) => {
        if (err1) return reject(err1)
        if (res.affectedRows == 1) return resolve("注册成功")
      })
    })
  })
}

// 登录
const login = (email, password) => {
  return new Promise((resolve, reject) => {
    db.query(`select * from user where email = "${email}"`, (err, result) => {
      if (err) return reject(err)
      if (result.length == 0) return reject("邮箱不存在，请先注册")
      if (result.length == 1) {
        // 密码比对
        let compareResult = bcrypt.compareSync(password, result[0].password)
        if (!compareResult) return reject('密码错误，请重新输入')
        // token生成
        const userInfo = {...result[0]}
        delete userInfo.password
        let token = jwt.sign(userInfo, secretKey, {expiresIn: '7d'})
        return resolve(token)
      }
    })
  })
}

module.exports = {
  setQrCode,
  getQrCode,
  register,
  login
}